package com.myFwk.aspect;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.alibaba.fastjson.JSON;
import com.myFwk.model.WebLog;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.annotation.Order;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Method;
import java.util.HashMap;

/**
 * @Title:
 * @Description:
 * @Author: guowl
 * @version： 1.0
 * @Date:2021/8/30
 * @Copyright: Copyright(c)2021 RedaFlight.com All Rights Reserved
 */
@Aspect
@Component
@Order(1)
@Slf4j
public class WebLogAspect {

    @Pointcut("execution( * com.myFwk.controller.*.*(..))")
    public void webLog() {

    }


    @Around(value = "webLog()")
    public Object recordWebLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        WebLog webLog = new WebLog();
        Object result = null;
        StopWatch stopWatch = new StopWatch(); //创建计时器
        stopWatch.start();
        result = proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());
        stopWatch.stop();
        //获取上下文请求
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        javax.servlet.http.HttpServletRequest request = requestAttributes.getRequest();
        //获取登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //获取登录方法
        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
        //获取方法名
        Method method = signature.getMethod();
        //获取方法上APIOperation注解
        ApiOperation annotation = method.getAnnotation(ApiOperation.class);
        //获取目标对象的类型名称
        String className = proceedingJoinPoint.getTarget().getClass().getName();
        //获取请求URL地址
        long totalTimeMillis = stopWatch.getTotalTimeMillis();
        String url = request.getRequestURL().toString();
        //获取方法参数的值
        Object[] args = proceedingJoinPoint.getArgs();
        webLog.setSpendTime((int) (totalTimeMillis) / 1000);
        webLog.setUri(request.getRequestURI());//设置请求URL
        webLog.setUrl(url);
        webLog.setBasePath(StrUtil.removeSuffix(url, URLUtil.url(url).getPath()));
        webLog.setUsername(authentication == null ? "anonymous" : authentication.getPrincipal().toString());
        webLog.setIp(request.getRemoteAddr());  // TODO 获取IP地址
        webLog.setDescription(annotation == null ? "no desc" : annotation.value());
        webLog.setMethod(className + "." + method.getName());
        webLog.setParameter(getMethodParamater(method, args));//存储的形式 key:参数名称 value:参数的值
        webLog.setResult(result);
        log.info(JSON.toJSONString(webLog,true));
        return result;

    }

    private Object getMethodParamater(Method method, Object[] args) {
        HashMap<String, Object> hashMap = new HashMap<>();
        LocalVariableTableParameterNameDiscoverer localVariableTableParameterNameDiscoverer =
                new LocalVariableTableParameterNameDiscoverer();
        String[] parameterNames = localVariableTableParameterNameDiscoverer.getParameterNames(method);
        for (int i = 0; i < parameterNames.length; i++) {
            hashMap.put(parameterNames[i], args[i]);
        }
        return hashMap;
    }
}
